<?php
include 'db_params.php';
// Include FB SDK
require 'facebook-php-sdk/src/facebook.php';

// Create our Application instance
$facebook = new Facebook(array(
  'appId'  => '123538731058282',
  'secret' => 'a62ca9342470d16a4d790003b2660ef5',
  'cookie' => true,
));
// Get session for checking
$session = $facebook->getSession();
  //Try to request FB variables
  try {
    $uid = $facebook->getUser();
    $me = $facebook->api('/me');
	} catch (FacebookApiException $e) {
	//If error on FB vars fetch -> need to login
	header('Location: http://www.need1partner.com/App/index.php?action=loginerror');
	}
  //If not session created may occur not registered, check if session exist and $me was fetched
  //if (!isset($_SESSION['need1partner']) AND $me)
  if (!isset($_SESSION['need1partner']))
	{
	//Check on db if user is registered
	$query = mysql_query("SELECT uid FROM users WHERE uid='$uid'");
	$r=mysql_num_rows($query); 
	//If not tuples fetched need to register
	if($r==0){
		header('Location: http://www.need1partner.com/App/registration.php');}
		//Session is created to speedup 
		else {
			$_SESSION['need1partner']=true;
		}
	}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MiPartner.CL</title>


<link href="css/styles.css" rel="stylesheet" type="text/css" /><!-- General Styles -->
<link rel="stylesheet" type="text/css" href="js/fancybox/jquery.fancybox-1.3.4.css" media="screen" /><!-- Fancybox -->
<link href="css/home-styles.css" rel="stylesheet" type="text/css" /><!-- Home Specific Styles -->

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> <!-- Jquery from Google CDN --> 
<script type="text/javascript" src="js/fancybox/jquery.mousewheel-3.0.4.pack.js"></script> <!-- FancyBox -->
<script type="text/javascript" src="js/fancybox/jquery.fancybox-1.3.4.pack.js"></script> <!-- FancyBox -->

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="js/utf8_decode.js"></script>
<script type="text/javascript" src="js/jquery.listselect.min.js"></script>

<script> var fuid=<?php echo $uid;?>;</script>
 <script>
 $(document).ready(function(){
	
	var x = document.getElementById('invitations');	
	var option;

	
	$.getJSON('functions/get_friends.php',{}, 
		function(data) {
			for(var i in data)
			{
			  option=document.createElement("option");
			  option.text=html_entity_decode(data[i]['name']);
			  option.value=data[i]['id'];
			  x.add(option,x.options[null]);
			}
			$("#invitations").listselect();
	   });
	
	});
	
	
	
	function ajax_CreateActivity()
	{
	$.fancybox.showActivity();
	var seleccionados = [];
	var seleccionados_names = [];

	
	for(var i=0 ; i < $('#invitations')[0].length ; i++)
	{
	seleccionados.push($('#invitations')[0][i].value);	
	seleccionados_names.push($('#invitations')[0][i].text);	

	}
	
	
	var name = $('#activity')[0][0].value;
	var details = $('#activity')[0][1].value;
	var date = $('#activity')[0][2].value;
	var place =  $('#activity')[0][3].value;
		
	
	
	$.ajax({
      url: "functions/create_activity.php",
      global: false,
      type: "POST",
      data: (
		{
		'fuid':fuid,
		'name':name ,
		'details': details,
		'date': date,
		'place': place ,
		'invitations': seleccionados
		}  	
	),
      dataType: "json",
      async:true,
      complete: function(){
         //$.fancybox.close();
		 $.fancybox.hideActivity();
		 
		 /*
		 var data="<h2>Haz invitado a:</h2><ul>";
		 for(var i in seleccionados)
		 {
			data=data+'<li>'+seleccionados_names[i]+' <input type="submit" onClick="javascript:notificar('+ seleccionados[i] +',"'+name+'","'+place+'");" value="Notificar por Facebook" /></li>';
		 }
		 data=data+'</ul>';
		 $('#inline1').html(data);
		 //
		 */
		 
		 $('#inline1').html('');
		 var foo = document.getElementById("inline1");
		 
		 $('#inline1').append('<h2>Haz invitado a:</h2><ul style="list-style-type: none;" >');
		 
		 for(var i in seleccionados)
		 {
		 
		 $('#inline1').append('<li style="list-style-type: none;">'+seleccionados_names[i]);
		 
		//Create an input type dynamically.
		var element = document.createElement("input");
		
		//Assign different attributes to the element.
		element.setAttribute("type", "submit");
		element.setAttribute("value", "Enviar notificación");
		element.setAttribute("onClick", 'notificar('+ seleccionados[i] +',"'+name+'","'+place+'");');
		
		

		
		//Append the element in page (in span).
		foo.appendChild(element);
		$('#inline1').append('</li>');
		 }
		 $('#inline1').append('</ul>');
		 
		 
		 //FB.ui({ method: 'apprequests', message: 'You should learn more about this awesome game.', data: 'http://need1partner.com', title: 'holi'});

      }
   });
	
	
	}
	
	function notificar(i,name,place)
	{
		msg = "Rodrigo te ha invitado a " + name + " en " + place; 
		FB.ui({ to:i , method: 'apprequests', message: msg , data: 'http://need1partner.com', title: 'Invitar a Participar de la Actividad'});
	}
	
		//$('option:selected',selobj).each( function() { vals.push( this.value ) } );

 </script>
	
	<script type="text/javascript">
    //<![CDATA[

    var customIcons = {
      restaurant: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
      bar: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      }
    };

    function load() {
      var map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(-33.385754, -70.583450),
        zoom: 10,
        mapTypeId: 'roadmap'
      });
      var infoWindow = new google.maps.InfoWindow;

      // Change this depending on the name of your PHP file
      downloadUrl("xmlgen.php", function(data) {
        var xml = parseXml(data);
        var locations = xml.documentElement.getElementsByTagName("location");
        for (var i = 0; i < locations.length; i++) {
				  var name = locations[i].getAttribute("name");
				  var address = locations[i].getAttribute("address");
				  var type = locations[i].getAttribute("type");
				  var point = new google.maps.LatLng(
					  parseFloat(locations[i].getAttribute("lat")),
					  parseFloat(locations[i].getAttribute("lng")));
				  var html = "" + name + " " + address;
				  var icon = {
								icon: "https://graph.facebook.com/"+name+"/picture",
								shadow: "http://labs.google.com/ridefinder/images/mm_20_shadow.png"
							  };
							  
				  var location = new google.maps.Marker({
					map: map,
					position: point,
					icon: icon.icon,
					shadow: icon.shadow
				  });
				  bindInfoWindow(location, map, infoWindow, html);
		}
      });
    }

    function bindInfoWindow(location, map, infoWindow, html) {
      google.maps.event.addListener(location, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
    }

    function downloadUrl(url, callback) {
      var request = window.ActiveXObject ?
          new ActiveXObject('Microsoft.XMLHTTP') :
          new XMLHttpRequest;

      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          request.onreadystatechange = doNothing;
          callback(request.responseText, request.status);
        }
      };

      request.open('GET', url, true);
      request.send(null);
    }

    function parseXml(str) {
      if (window.ActiveXObject) {
        var doc = new ActiveXObject('Microsoft.XMLDOM');
        doc.loadXML(str);
        return doc;
      } else if (window.DOMParser) {
        return (new DOMParser).parseFromString(str, 'text/xml');
      }
    }

    function doNothing() {}

    //]]>

</script>

</head>

 <div id="fb-root"></div> <!-- Facebook requiered div!! -->

<script> <!-- Facebook Init scripts -->
      window.fbAsyncInit = function() {
        FB.init({
          appId   : '123538731058282',
		  status  : true, // check login status
          cookie  : true, // enable cookies to allow the server to access the session
          xfbml   : true // parse XFBML
        });

        // whenever the user logs in, we refresh the page
        FB.Event.subscribe('auth.login', function() {
          window.location="dashboard.php";
        });
      };

      (function() {
        var e = document.createElement('script');
        e.src = document.location.protocol + '//connect.facebook.net/es_ES/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
      }());
</script>
    
<script>
$(document).ready(function(){


$('#various3').click(function() {
  load();
});


$("#various1").fancybox({
			'titlePosition'		: 'inside',
			'transitionIn'		: 'none',
			'transitionOut'		: 'none'
		});
$("#various2").fancybox({
			'titlePosition'		: 'inside',
			'transitionIn'		: 'none',
			'transitionOut'		: 'none'
		});
$("#various3").fancybox({
			'titlePosition'		: 'inside',
			'transitionIn'		: 'none',
			'transitionOut'		: 'none'
		});
});
</script>
    
<div class="container">

  <div class="sidebar1">
  
      <div id="home_right">
  
        <h3>Bienvenido</h3>
        <p><?php echo $me['name']; ?></p>
        <p><img src="https://graph.facebook.com/<?php echo $uid; ?>/picture" /></p>
      	<ul>
        <a id="various1" href="#inline1">Nueva Actividad</a><br />
        <a id="various2" href="#inline2">Buscar Actividades</a><br />
        <a id="various3" href="#inline3">Ver Mapa</a><br />
		</ul>
      </div>


  </div><!-- end .sidebar1 -->
  
  <div class="content">
  
  <div id="main-content">

	<!-- Fancy Box-->
	<div id="dimbox" style="display: none;">

		<div id="inline1" style="width:800px;height:400px;overflow:auto;margin-top:35px;margin-left:35px;">
		<h3>Crear nueva Actividad</h3>
        <form id="activity" action="" method="get">
        <label>Nombre de Actividad<input  name="name" type="text" /></label><br />
        <label>Detalles<input  name="details" type="text" /></label><br />
        <label>Fecha/Hora<input  name="date" type="text" /></label><br />
        <label>Lugar<input  name="place" type="text" /></label><br /><br />
        <label for="select">Seleccione amigos a invitar<br /><br />
        </label>
        <select name="invitations" size="10" id="invitations">
        </select>
        <input type="button" value="Crear Actividad" onClick="ajax_CreateActivity(this);" />
        </form>
		
		</div>
	

		<div id="inline2" style="width:400px;height:200px;overflow:auto;margin-top:35px;margin-left:35px;">
		<h3>En construccion</h3>	
		</div>
	


		<div id="inline3" style="width:1000px;height:400px;overflow:auto;">
		    <div id="map" style="width: 1000px; height: 400px"></div>	
		</div>

	</div>

<!-- -->

  <p>&nbsp;</p>
  <div class="col-left">
  	<h2 class="heading" style="section heading">MiPartner</h2>
  	<span class="sub-heading">El lugar para interactuar con tus vecinos y amigos cercanos!</span>
  </div>
  <span class="thanks">  Muchas gracias! Muy pronto lanzaremos la primera versión de este servicio y tu serás el primero en saberlo!
  <p style="margin-top:20px;"><fb:like href="need1partner.com" send="false" show_faces="false" font="" width="200"></fb:like></p>
  </span>

  <div id="amigos"> 
  <h1 class="heading">Mis Amigos</h1>
<?php

$result = @mysql_query("SELECT other.name as ff, other.uid as fuid FROM users as other, friends as friend WHERE friend.uid = '$uid' and friend.fid=other.uid group by(other.name)");

while($row = mysql_fetch_array($result))
  {
echo '<p><img src="https://graph.facebook.com/'.$row['fuid'].'/picture">';
echo '&nbsp;<a href="https://www.facebook.com/profile.php?id='.$row['fuid'].'">'.utf8_encode ($row['ff']).'</a></p>';
  }

$result = @mysql_query("SELECT other.name as ff, other.uid as fuid FROM users as other, friends as friend WHERE friend.uid = '$uid' and friend.fid=other.uid group by(other.uid) order by(other.uid) desc");
echo '<script>';
echo 'var fuids = [];';
while($row = mysql_fetch_array($result))
  {
echo 'fuids.push('.$row['fuid'].');';
  }

echo '</script>';
?>
</div>
<div id="vecinos">
    <h1 class="heading">Mis Vecinos</h1>
<?php
$center_lat='-33.385864';
$center_lng='-70.583389';
$radius='20'; //in kms

$result = @mysql_query("SELECT users.uid as uid, users.name as nombre,otherlocations.lat as lat,otherlocations.lng as lng, ( 3959 * 1.609344 * acos( cos( radians('$center_lat') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('$center_lng') ) + sin( radians('$center_lat') ) * sin( radians( lat ) ) ) ) AS distance FROM locations as otherlocations, users as users WHERE (otherlocations.id=users.home_location) HAVING distance < '$radius' ORDER BY distance LIMIT 0 , 20");

while($row = mysql_fetch_array($result))
  {
echo '<p><img src="https://graph.facebook.com/'.$row['uid'].'/picture">';
echo '&nbsp;<a href="https://www.facebook.com/profile.php?id='.$row['uid'].'">'.utf8_encode($row['nombre']).'</a> - '.round($row['distance'],2).' kms</p>';
  }
?>
</div>

<div id="actividades">
    <h1 class="heading">Actividades</h1><br />
<?php
$center_lat='-33.385864';
$center_lng='-70.583389';
$radius='20'; //in kms

$result = @mysql_query("SELECT name FROM activities where createdby='$uid' order by id desc limit 5");

while($row = mysql_fetch_array($result))
  {
echo '<p>'.$row['name'].'</p>';
  }
?>
</div>

  </div>
  </div>
  <div class="footer">
    <p>MiPartner.cl - Proyecto Emprendimiento Escuela de Ingenieria UC</p>
  <!-- end .footer --></div>
  <!-- end .container --></div>
</body>
</html>